<?php

/**
 * 登陆控制器
 *
 * @author dalei.chen
 */

require 'CommonController.php';

class Admin_DayDataExcelResendController extends Admin_CommonController
{
    /**
     * 
     * 路径密码
     */
    private $_passid = 'yekbi123';
    private $_currAction = '';
    private $_productcode = '';
    private $_reportFile = '';
    private $_reportDay = '';

    /**
     * 初始化
     * 
     * @return void
     */
    public function init()
    {
        $this->_loginIsCheck = 1;
        parent::init();
        $this->view->title = $this->_configs['project']['systemName'] . " - 管理中心";
        $this->_model = new Application_Model_DayDataCombine();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_reportDay = date('Y-m-d',strtotime(("-1 day")));
       

       
    }
    /**
     * 时间选定（BI后台指定）
     * Enter description here ...
     */
    public function getReportDay() 
    {
    	$filter = new Zend_Filter_StripTags();
        $this->_reportDay = $filter->filter(trim($this->_request->getPost('startTime')));
        
    }
    /**
     * 获取月报表标题（默认为今天算起）
     */
    public function getMonthReportTitle()
    {
    	$yestoday = strtotime($this->_reportDay);
    	return date('Y年m月',$yestoday+24*60*60);
    }
    /**
     * 获取报表TITLE(默认为昨天)
     */
    public function getFileDay()
    {
    	return $this->_reportDay;
    }
    
    /**
     * 获取日报发送时间(默认为昨天)
     */
    public function getPositionDay()
    {
    	return $this->_reportDay;
    }
    /**
     * 获取指定日期的时间戳(默认为昨天)
     */
    public function getPositionStamp()
    {
    	return strtotime($this->_reportDay);
    }
    /**
     * 手动发送日报的视图文件
     * Enter description here ...
     */
    public function reportAction()
    {
    	$pCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$this->view->product = $this->_productModel->fetchRow("code = '{$pCode}'");
    	$this->view->subtitle = '手动发送日报';
    	$this->view->defDate = $this->_reportDay;
    	$this->view->actionUrl =  $this->view->projectUrl(array('action'=>'do-report'));
    	$this->renderScript('day-data-excel-resend/report.php');
    }
   

    /**
     * 报表导出，
     * 发送下载地址 $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/dayData/';
     * 生成表格
     * 发送信息到邮箱
     * 
     * @return void
     */
    public function doReportAction()
    {
    	//获取当前的产品数据
    	$pCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        if($this->_request->isPost()){
         	//设定日期       
         	$this->getReportDay();
            $startTime = $this->getPositionDay();

            //获取搜有需要发送的报表产品编号
            $productCodes = array($pCode);
            
            foreach ($productCodes as $productCode) {
                $product = $this->_productModel->fetchRow("code = '{$productCode}'");
                $productName = $product['name'];
                //日运营表
                $opRow = $this->dayMemberType($startTime,$productCode);
                $keyOpArr = array('渠道类型', '订单金额', '订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                
                );
                
                 //发送其他渠道的（没有广告排期的订单日报）到指定邮箱
                $opOtherRow = $this->dayMemberTypeOther($startTime,$productCode);
                $keyOpOtherArr = array('渠道类型', '订单金额', '订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                );
                
                //广告投放表
                $adRow = $this->dayAd($startTime, $productCode);
                
                //付费广告表
                $adPaidRow = $adRow['rowPaid'];
                $keyAdPaidArr = array('广告渠道', 'ROI', '订单金额', '订单量', '客单价', '广告成本', '激活量');
                
                //操作系统报表
                $osRow = $this->dayOs($startTime,$productCode);
                $keyOsArr = array('操作系统', '订单金额', '订单量', '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额');
                
                
                //发送其他渠道的（没有广告排期的订单日报）到指定邮箱
                $opOtherErrorRow = $this->dayMemberTypeOtherError($startTime,$productCode);
                $keyOpOtherErrorArr = array('SourceId', '订单金额' ,'订单量', 
                                  '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额'
                );
                
                //获取月明细报表
                $monthReportRow = $this->monthReport($productCode);
                $keyMonthReportRow = array('日期','渠道类型','渠道名称','操作系统', 'ROI','当天总提交订单金额',
                    '当天总提交订单量','客单价','广告成本',
                    '激活量','当天激活用户订单量',
                    '当天激活用户提交订单转化率',  '当天激活用户订单金额',
                    '当天ROI',
                     '启动次数','启动人数','人均启动'                      
                );
                //获取月明细报表-有广告排期的
                $monthAdReportRow = $this->monthAdReport($productCode);
                //获取月明细报表-无广告排期的
                $monthFreeReportRow = $this->monthFreeReport($productCode);
                
               
                $yestoday = date('Y-m-d',strtotime("-1 day"));
                //收集其他简报的数组
                $simpleReportRows = array(
                                    'opRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 运营日报','title'=>$keyOpArr,'lines'=>$opRow),
                                    'opOtherRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 广告投放日报','title'=>$keyAdPaidArr,'lines'=>$adPaidRow),
                                    'adPaidRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 其他渠道日报','title'=>$keyOpOtherArr,'lines'=>$opOtherRow),
                                    'osRow' => array('name'=>$this->getFileDay().' - '.$productName.' - 操作系统报表','title'=>$keyOsArr,'lines'=>$osRow)    
                                    );
                //写入到月运营报表EXCEL文件
                $monthReportFile = $this->_model->writeToExcelMonth('monthReport', $this->getMonthReportTitle().' '.$productName.' 月运营报表 ',$monthReportRow, $monthAdReportRow,$monthFreeReportRow,$productCode,$productName,$keyMonthReportRow, $simpleReportRows);

                //发送邮件到用户邮件
                $mailList = explode(',',$this->_request->getPost('sendReportMail'));
                $to = array();
                foreach ($mailList as $mail) {
                    $to[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }
                           
                if (count($to)) {
                    //收集所有表格数据
                    $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
                    $data = array();
                    $data[]=array(
                    'title'=>'日运营报表',
                    'headLine' => $keyOpArr,
                    'bodyLines' => $opRow,
                    'file' => ''
                    );
                    $data[]=array(
                    'title' => '广告投放报表',
                    'headLine' => $keyAdPaidArr,
                    'bodyLines' => $adPaidRow,
                    'file' => ''
                    );
                    $data[]=array(
                    'title' => '操作系统报表',
                    'headLine' => $keyOsArr,
                    'bodyLines' => $osRow,
                    'file' => ''
                    );
                    $data[] = array(
                    'title' => '日运营报表 - 免费渠道明细',
                    'headLine' => $keyOpOtherArr,
                    'bodyLines' => $opOtherRow,
                    'file' => ''
                    );
                    
                    //写入到日报的HTML文件
                	//$dayReportHtmlFile = $this->_model->writeToHtmlFile($data,array(),array(), $productName.' - 日报',$productName, PUBLIC_PATH . "/data/dayData/".$this->getFileDay().'_'.$productCode."_dayReportHtml.html");
                	$dataMonth = array();
                	$dataMonth[] = array(
                	'title'=>'月运营报表',
                	'headLine' => $keyMonthReportRow,
                	'bodyLines' => $monthReportRow,
                	'file' => ''
                	);
                	//写入到总月报的HTML文件
                	//$monthReportHtmlFile =  $this->_model->writeToHtmlFile($monthReportRow, $monthAdReportRow, $monthFreeReportRow, $productName.' - 所有渠道月报',$productName, PUBLIC_PATH . "/data/dayData/".$this->getFileDay().'_'.$productCode."_monthReportHtml.html", 1,$keyMonthReportRow);
                	
                    $dataAdMonth = array();
                	$dataAdMonth[] = array(
                	'title'=>'月运营报表-广告渠道',
                	'headLine' => $keyMonthReportRow,
                	'bodyLines' => $monthAdReportRow,
                	'file' => ''
                	);
                	
                	
                	//发送运营日报表邮件 
                    $mainMail = $this->_request->getPost('reportMail'); 
                    
					 //加载ZIP类
					  Zend_Loader::loadClass('Project_PclZip');
					  $attFilePath = PUBLIC_PATH . "/data/dayData/".$productCode.'_'.date('YmdHis').'_archive.zip';
					  if(file_exists($attFilePath)) {
					  	unset($attFilePath);
					  }
                	  $archive = new Project_PclZip($attFilePath);
                	  $vList[] = $archive->add(PUBLIC_PATH . "/data/dayData/".$monthReportFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/"); 
                      /*       
                      $vList[] = $archive->add($monthReportHtmlFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/"); 
                                    
                      $vList[] = $archive->add($dayReportHtmlFile, 
                                    PCLZIP_OPT_REMOVE_PATH, PUBLIC_PATH . "/data/dayData/");  
                      */             
                                                     
		              foreach ($vList as $item) {
			              if ($item == 0) {
					          die("Error : ".$archive->errorInfo(true));
					      }
		              }
				      $atts = array(
					        array('filename'=>$this->getFileDay().'_'.$productCode.'_att.zip','path'=>$attFilePath,'type'=>'application/zip')
						); 
                    $this->_model->sendMail('', '', ''
                    ,$productName.' '.$startTime.' 运营日报','运营日报',$productName,$mainMail,$to,$data,$atts,2);      
                }

                //发送邮件到用户邮件
                $mailListOther = $this->_configs['project']['reportTestMail'];
                $toOtherError = array();
                foreach ($mailListOther as $mail) {
                    $toOtherError[]=array(
                    'name'=>$mail,'email'=>$mail
                     );
                }

                if (count($toOtherError)) {
                    //收集所有表格数据
                    $downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
                    $dataOther = array();
                    $dataOther[]=array(
                    'title'=>'日运营报表',
                    'headLine' => $keyOpOtherErrorArr,
                    'bodyLines' => $opOtherErrorRow,
                    'file' => ''
                    );
                    //发送运营日报表邮件        
                    $mainMailOther = $toOtherError[0]['email'];
                    array_shift($toOtherError);
                    if (count($opOtherErrorRow)) {
                        $this->_model->sendMail('','','',$productName.' '.$startTime.' 运营日报-异常渠道','运营日报-异常渠道',$productName,$mainMailOther,$toOtherError,$dataOther,null,2);
                    }
                    
                }  
                
            }
        } exit();
    }
    
    /**
     * 日运营报表-日
     */
    public function dayMemberType($startTime,$productCode)
    {               
        $rows = $this->_model->getDayMemberType($startTime,$productCode);
        $totalRow = array();
        $memberType = array('广告渠道','免费渠道');
        for ($i=0; $i<count($rows); ++$i) {
            array_unshift($rows[$i], $memberType[$i]);
            foreach ($rows[$i] as $key=>$val) {
                if ($key != 'memberType') {
                    @$totalRow[$key] += floatval($val);  
                }          
            }           
        }
         //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        
        $rows[$i] = $totalRow;
                       
        array_unshift($rows[$i], '总计');       
        return $rows;   
    }
    
     /**
     *日报 - 非排期渠道
     */
    public function dayMemberTypeOther($startTime,$productCode)
    {
        $totalRow = array();
        $rowsPaid = $this->_model->getMemberTypeOther($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
              
            $rowsPaid[$i] =$totalRow;
              
            array_unshift($rowsPaid[$i], '总计');
        }
        
        return $rowsPaid;
        
    }
    
     /**
     *日报 - SOURCEID不存在的渠道信息
     */
    public function dayMemberTypeOtherError($startTime,$productCode)
    {
        $totalRow = array();
        $rowsPaid = $this->_model->getMemberTypeOtherError($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'sourceId' && $key != 'sourceSubId') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
              
            $rowsPaid[$i] =$totalRow;
            array_unshift($rowsPaid[$i], '总计');
        }
        
        return $rowsPaid;
    }
    
     /**
     * 广告投放-日
     */
    public function dayAd($startTime,$productCode)
    {               
        //付费广告
        $totalRow = array();
        $rowsPaid = $this->_model->getDayPaidAd($startTime, $productCode);
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=floatval($val);
                    } 
                }           
            }
              //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
            @$totalRow['ROI'] =  $totalRow['okOrderAmount']/$totalRow['adPrice'];
              
            $rowsPaid[$i] =$totalRow;
              
            array_unshift($rowsPaid[$i], '总计');
        }
        return array(
        'rowPaid'=>$rowsPaid
        );
        
    }
    
   /**
     * 操作系统 - 日
     */
    public function dayOs($startTime,$productCode)
    {
        //日运营按操作系统统计报表
        $totalRow = array();
        $rows = $this->_model->getDayOs($startTime, $productCode);      
        if (count($rows)) {
            for ($i=0; $i<count($rows); ++$i) {           
                foreach ($rows[$i] as $key=>$val) {
                    if ($key != 'osName') {
                        @$totalRow[$key]+=floatval(($val));
                    } 
                }           
            }
             //客单价统计
            @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
            $rows[$i] = $totalRow;
            array_unshift($rows[$i], '总计');
        }
        
        return $rows;   
    }
    
  
    /**
     * 报表文件下载
     */
    public function downReportAction()
    {
    	$this->_reportFile = $this->_request->get('file');
    	$this->_currAction = 'down-report';
    	
    	 if (Application_Model_UserLogin::isLogined()) {
    	 	echo '用户验证成功，请下载。';
    	 	//$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/yek_mob/data/dayData/';
    	 	$downUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/data/dayData/';
    	 	$this->logout();
    	 	redirect($downUrl . $this->_request->get('file'));
    	 	exit();
    	 } else {
        	redirect($this->view->projectUrl(array('action'=>'login-file','file'=>$this->_reportFile)));
            exit();
        }
    }
    
    /**
     * 获取最近30天的明细报表
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthReport($productCode)
    {
        $start = $this->getPositionStamp();
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< date('d',$start); ++$i) {
            $startTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_model->getDayMemberAdDetail($productCode,$startTime);
        }
        //获取总计
        $startTime = date("Y-m-d",$this->getPositionStamp());
        $endTime = date("Y-m-01",$this->getPositionStamp());
        $totalRow = $this->_model->getMonthTotal($productCode,$startTime,$endTime);
        //获取平均
        $avgRow = $this->_model->getMonthAvg($productCode,$startTime,$endTime);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    /**
     * 获取最近30天的明细报表(广告投放)
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthAdReport($productCode)
    {
        $start = $this->getPositionStamp();
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< date('d',$start); ++$i) {
            $startTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_model->getAdDayMemberAdDetail($productCode,$startTime);
        }
        //获取总计
        $startTime = date("Y-m-d",$this->getPositionStamp());
        $endTime = date("Y-m-01",$this->getPositionStamp());
        $totalRow = $this->_model->getAdMonthTotal($productCode,$startTime,$endTime);
        //获取平均
        $avgRow = $this->_model->getAdMonthAvg($productCode,$startTime,$endTime);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    
    /**
     * 获取最近30天的明细报表(免费渠道)
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthFreeReport($productCode)
    {
        $start = $this->getPositionStamp();
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< date('d',$start); ++$i) {
            $startTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_model->getFreeDayMemberAdDetail($productCode,$startTime);
        }
        //获取总计
        $startTime = date("Y-m-d",$this->getPositionStamp());
        $endTime = date("Y-m-01",$this->getPositionStamp());
        $totalRow = $this->_model->getFreeMonthTotal($productCode,$startTime,$endTime);
        //获取平均
        $avgRow = $this->_model->getFreeMonthAvg($productCode,$startTime,$endTime);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
}